package com.swxy.club.interceptor;


import com.swxy.club.dto.bo.CurrentUserBO;
import com.swxy.club.utils.SessionUtil;
import com.swxy.club.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 易
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            try {
                CurrentUserBO currentUser = SessionUtil.getCurrentUser(token);
                if (currentUser != null) {
                    UserContext.setCurrentUser(currentUser);
                }
            } catch (Exception e) {
                log.warn("token解析失败");
            }
        }
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        UserContext.clear();
    }
}
